import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

# Load the dataset
url = "https://raw.githubusercontent.com/MicrosoftDocs/mslearn-introduction-to-machine-learning/main/Data/ml-basics/penguins.csv"
df = pd.read_csv(url)

# Printing the first 5 rows of the dataset
print(df.head())

# Visualize the distribution of the penguins species with a bar plot in matplotlib
plt.figure(figsize=(10, 6))
sns.countplot(x='Species', data=df)
plt.title('Distribution of Penguin Species')
plt.show()

# Visualize with boxplots how the FlipperLength, CulmenLength and CulmenDepth are distributed for each species
plt.figure(figsize=(12, 8))
sns.boxplot(x='Species', y='FlipperLength', data=df)
plt.title('Flipper Length Distribution by Species')
plt.show()

sns.boxplot(x='Species', y='CulmenLength', data=df)
plt.title('Culmen Length Distribution by Species')
plt.show()

sns.boxplot(x='Species', y='CulmenDepth', data=df)
plt.title('Culmen Depth Distribution by Species')
plt.show()

# Show rows with missing values
print(df[df.isnull().any(axis=1)])

# Drop rows with missing values
df = df.dropna()

# Split the data into features and labels
features = df[['CulmenLength', 'CulmenDepth', 'FlipperLength']]
labels = df['Species']

# Split the data into training and test sets in a way to have 30% of the data for testing
X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.3, random_state=42)

# Create a multiclass Logistic Regression model
model = LogisticRegression(multi_class='multinomial', solver='lbfgs', max_iter=200)

# Train the model
model.fit(X_train, y_train)

# Predict the labels of the test set
y_pred = model.predict(X_test)

# Calculate the accuracy of the model
accuracy = accuracy_score(y_test, y_pred)
print(f'Model Accuracy: {accuracy:.2f}')